package org.fjsei.yewu.aop;

import org.hibernate.exception.GenericJDBCException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalDatabaseExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalDatabaseExceptionHandler.class);

    private final DatabaseClusterMonitor clusterMonitor;

    public GlobalDatabaseExceptionHandler(DatabaseClusterMonitor clusterMonitor) {
        this.clusterMonitor = clusterMonitor;
    }

    @ExceptionHandler({GenericJDBCException.class, DataAccessException.class})
    public void handleDatabaseExceptions(Exception ex) {
        if (ex.getMessage() != null &&
                (ex.getMessage().contains("replica unavailable") ||
                        ex.getMessage().contains("lost quorum"))) {

            logger.error("Database cluster failure detected in exception handler: {}", ex.getMessage());

            // 立即进入维护模式
            if (clusterMonitor.isServiceEnabled()) {
                clusterMonitor.enableMaintenanceMode();
            }
        }
    }
}
